package com.fuchuang.seckillsystem.config;

import com.fuchuang.seckillsystem.utils.KieSessionUtils;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.kie.spring.KModuleBeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.io.File;
import java.io.IOException;


/**
 * 规则引擎配置类
 */
@Configuration
public class DroolsConfig implements EnvironmentAware {
    
    private static final KieServices kieServices = KieServices.Factory.get();
    
    //解决Config类中无法通过@Value读取到yml中数据
    private static Environment environment;
    
    @Bean(name = "kieBase")
    @ConditionalOnMissingBean
    public static KieBase getKieBase() throws IOException {
        //获取规则文件所在目录
        String filePath = environment.getProperty("rules.filePath");
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        File file = new File(filePath);
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            for (File f : files) {
                if (f.isFile() && f.getName().endsWith(".xls")) {
                    System.out.println(f.getName());
                    String resultFileName = KieSessionUtils.getDRL(filePath, f.getName());
                    kieFileSystem.write(ResourceFactory.newFileResource(new File(filePath + resultFileName)));
                }
            }
        }
        KieRepository kieRepository = kieServices.getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();
        KieContainer kieContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
        return kieContainer.getKieBase();
    }
    
    
    @Bean
    @ConditionalOnMissingBean
    public KModuleBeanFactoryPostProcessor kiePostProcessor() {
        return new KModuleBeanFactoryPostProcessor();
    }
    
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}